package com.lmx.repoDomain.repository;

import io.katharsis.queryParams.QueryParams;
import io.katharsis.repository.annotations.JsonApiFindAll;
import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.constants.CommonConstants;
import com.lmx.persistence.service.FoodService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.Food;

/**
 * 食物
 *
 * @author ytche
 * @date 2017年8月30日
 *
 */
@JsonApiResourceRepository(value = Food.class)
@Component
public class FoodRepository extends BaseRepository<Food> {
	@Autowired
	private FoodService service;

	@PostConstruct
	public void init() {
		super.dslJpaService.setEntityClass(Food.class);
	}

	@Override
	@JsonApiFindAll
	public Iterable<Food> findAll(final QueryParams requestParams) {
		return super.findAll(requestParams);
	}

	@Override
	@JsonApiSave
	public Food save(Food model) {
		if (model.getId() == null) {
			model = super.save(model);
		} else {
			if (model.getDelStatus() == 1) {// 删除
				// 删除 验证 CustomerFoodPlan errorcode 8
				int deleteFlag = service.checkFoodRelations(model);
				if (deleteFlag > 0) {
					model.setErrcode(8);// no delete
					throw new BusinessException(null, CommonConstants.ERROR_CODE.NO_DELETE.label(), null);
				}
				dslJpaService.update(model);
			} else {
				dslJpaService.update(model);
			}
		}
		return model;
	}

}
